package com.devshephard.lock;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

public class ReentrantLockDemo {

    public static void main(String[] args) throws InterruptedException {

       /* for (int i = 0; i < 10; i++) {
            new Thread(()->{

                try {
                    //testSync(Thread.currentThread().getName());
                    testReentLock(Thread.currentThread().getName());
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

            }).start();
        }*/

        new Thread(()->{
            try {
                testCondition(Thread.currentThread().getName());
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        },"A").start();

        TimeUnit.SECONDS.sleep(5);

        new Thread(()->{
               reentrantLock.lock();
               condition_1.signalAll();
               reentrantLock.unlock();
        },"B").start();

    }

    public static ReentrantLock reentrantLock = new ReentrantLock();



    public static Condition condition_1 = reentrantLock.newCondition();

    public static void testCondition(String threadName) throws InterruptedException {

        try {
            reentrantLock.lock();
            System.out.println(threadName + " 进入休息室等待！");
            condition_1.await();
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            System.out.println(threadName + " 被其他线程唤醒");
            reentrantLock.unlock();
        }

    }

    public static void testReentLock(String threadName) throws InterruptedException {

        try {
            reentrantLock.lock();
            System.out.println(threadName);
            TimeUnit.SECONDS.sleep(2);
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            reentrantLock.unlock();
        }

    }

    public static synchronized void testSync(String threadName) throws InterruptedException {

        System.out.println(threadName);
        TimeUnit.SECONDS.sleep(2);

    }

}


